package ph.com.gs3.formalistics.view.valueobjects.parsers;

import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.valueobjects.business.form.Form;
import ph.com.gs3.formalistics.view.documentview.DocumentViewDataExtractor;

public class UserActionListViewItemParser {

	public static final String TAG = UserActionListViewItemParser.class.getSimpleName();

	public static final String USER_ACTION_LIST_ITEM_DATE_FORMAT = "MMM d";

	public static String formatDate(String rawDateString) {

		try {
			Date rawDate = DateUtilities.parseToServerDate(rawDateString);
			return DateUtilities.WIDGET_DISPLAY_DATE_ONLY_FORMAT.format(rawDate);
		} catch (ParseException e) {
			FLLogger.d(TAG, "Failed to parse date: " + rawDateString);
			e.printStackTrace();
		}

		return "";

	}

	public static String generateUserActionListItemContentsFromFields(Form form, JSONObject formFields) {

		FLLogger.d(TAG, formFields.toString());
		
		String contents = "";
		int keyCount = 0;

		Iterator<?> keys = formFields.keys();

		while (keys.hasNext() && keyCount < 3) {
			keyCount++;
			String key = (String) keys.next();
			try {
				String line = escapeContentValues(formFields.getString(key));

				if (!line.isEmpty()) {
					// contents += key + " " + line + "\n";
					contents += line + "\n";
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		// remove the trailing \n
		// contents = contents.substring(0, contents.length() - 2);
		if (!contents.isEmpty()) {
			contents = contents.substring(0, contents.length() - 1);
		}

		return contents;

	}

	public static String escapeContentValues(String contentValues) {

		String escapedContentValues = contentValues.replace(
		        DocumentViewDataExtractor.SERVER_MULTI_VALUE_SEPARATOR, ",");

		return escapedContentValues;

	}

}
